/**
 * File: ArrayStore.java
 * Created by: mhaimel
 * Created on: 9 Jul 2009
 * CVS:  $Id: ArrayStore.java,v 1.2 2009/10/09 15:18:24 mhaimel Exp $
 */
package uk.ac.ebi.curtain.service.impl;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;

import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import uk.ac.ebi.curtain.service.IdentifierStore;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;

/**
 * @author mhaimel
 *
 */
public class ArrayStore<O> implements IdentifierStore<Integer, O> {
	private final Log log = LogFactory.getLog(this.getClass());
	private final AtomicReference<AtomicReferenceArray<O>> array = new AtomicReference<AtomicReferenceArray<O>>(new AtomicReferenceArray<O>(0));
	
	public ArrayStore() {
		// do nothing
	}
	
	private AtomicReferenceArray<O> _getArray(){
		return array.get();
	}

	public void clear() {
		reset(0);
	}

	public O getIdentifier(Integer input) {
		return 
			_getArray()
				.get(
					input);
	}

	public O getOrAddIdentifier(Integer input) {
		if(hasIdentifier(input)){
			return getIdentifier(input);
		} else {
			throw new CurtainUncheckedException(
					"Identifier "+input+" out of range from " +  _getArray().length() +"! Automatic adding not supported");
		}
	}

	public boolean hasIdentifier(Integer input) {
		return input >= 0 && _getArray().length() > input;
	}

	public void reset(Integer size) {
	    AtomicReferenceArray<O> arr = new AtomicReferenceArray<O>(size);
	    this.array.set(arr);
	    for (int i = 0; i < size; ++i) {
	    	arr.set(i, null);
	    }
	}

	public void registerIdentifier(Integer input, O output) {
		_getArray().set(input, output);
	}

	public Integer getSize() {
		return _getArray().length();
	}

	public Iterable<Integer> getKeys() {
		throw new NotImplementedException("Funktionality not yet implemented!");
	}
}
